// ----------------------------------------------------------------
//  Global constants and variables
// ----------------------------------------------------------------

MAP_HOLDER = '#map';
SM_THRESHOLD = 768; // below this threshold is screen considered as small

var $holder = null;
var map = null;
var timeSlider = null;
var _amounts = {};
var _organization = 'TWB';
var _countryId = null;
var _interval = [2010,2013];
var _perCapita = false;

// ----------------------------------------------------------------
//  Map Control Code 
// ----------------------------------------------------------------

// this function is called after the main page is loaded
function initMapControl() {
    // initialize sidebar
    createTimeSlider();

    // initialize map
    $holder = $(MAP_HOLDER);
    map = kartograph.map(MAP_HOLDER);
    prepareMap();

    // event bindings
    $(window).resize(function() {
        redrawSidebar();
        resizeMap();
    });

    // initialize search
    initializeSearchBox();

    getData(_organization, _interval);
}

// ----------------------------------------------------------------
//  Data requests
// ----------------------------------------------------------------

/*
 * Ajax call for obtaining data about financial aid
 */
function getData(organization, interval) {
    $.ajax({
        url: "/interface/get-data",
        datatype: "json",
        data: {"organization": organization, "interval": interval},
        success: dataDelivered,
        failure: function(data) { 
            console.log('Data request failed');
        }
    });
}

/*
 * Process data after they are delivered
 */
function dataDelivered(response) {
    //console.log(response);
    //_amounts = JSON.parse(response);
    if (response['TWB'] && response['UNDP']) {
        _organization = 'TWB+UNDP'
    } else if (response['UNDP']) {
        _organization = 'UNDP'
    } else {
        _organization = 'TWB'
    }
    _interval = response['interval'];
    _amounts = response['countries'];
    updateInfobox(_countryId);
	colorMap();
}

/*
 * Calculate amout of money which was given to country with an id
 * during an interval by an organization
 */
function getIntervalAmount(id, interval, organization) {
    if (arguments.length == 1) {
        interval = _interval;
        organization = _organization;
    }
    if (organization == 'TWB+UNDP') {
        var organizations = ['TWB','UNDP'];
    } else {
        var organizations = [organization];
    }
    var total = 0;
    for (var i = 0; i < organizations.length; i++) {
        for (var year = interval[0]; year <= interval[1]; year++) {
            total += getAmount(id, year, organizations[i]);
        }
    }
    return total;
}

/*
 * Return amout of money which was given to an country in chosen year
 * by an organization
 */
function getAmount(id, year, organization) {
    if (!(id in _amounts)) {
        return 0;
    }
		
    var amount = _amounts[id][organization][year];
    if (_perCapita) {
		if (!(id in countries)) {
			return 0;
		}
        var population = countries[id]['population'];
        amount /= population;
    }
    return amount;
}

// ----------------------------------------------------------------
//  Options change
// ----------------------------------------------------------------

/*
 * Change selected organization
 */
function changeOrganzation(organization) {    
	switch (organization) {
		case 'UNDP':
			$('#organisation').html('UNDP <span class="caret"></span>');
			break;
		case 'TWB':
			$('#organisation').html('World Bank <span class="caret"></span>');
			break;
		default:
			$('#organisation').html('World Bank & UNDP <span class="caret"></span>');
			break;
	}
	_organization = organization;
	getData(organization, _interval);
	//updateInfobox(_countryId);
}


/*
 * Change selected time interval
 */
function changeTimeInterval(fromYear, toYear) {
	_interval = [fromYear, toYear];
	getData(_organization, _interval);
	//updateInfobox(_countryId);
}

/*
 * Change per-capita option
 */
$('#perCapitaCheckbox').change(function() {
    _perCapita = this.checked;
    updateInfobox(_countryId);
    colorMap();
});
